<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>静态建表</title>
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/custom.form.css">
    <style>
        .table-wrapper {
            overflow-x: auto;
            width: 100%;
        }

        #resultTable {
            margin-top: 20px;
            border-collapse: collapse;
            min-width: 1000px; /* 或你自定义的宽度，用于触发滚动条 */
            text-align: center;
        }

        #resultTable th,
        #resultTable td {
            text-align: center;
            word-break: keep-all;
            border: 1px solid #ddd;
            padding: 8px;
        }

        #resultTable th {
            background-color: #f2f2f2;
        }

        .show_import_excel {
            text-align: center;
            font-size: 18px;
            margin-top: 20px;
            color: #333;
        }


    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header"></div>
                <div class="layui-card-body">
                    <!--新建表格-->
                    <div class="panel panel-default operation_case" hidden>
                        <div class="panel-heading title"></div>
                        <div class="layui-card-body">
                            <form class="layui-form" action="javascript:void(0)" lay-filter="deptInfo"
                                  style="margin-top: 10px">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">表格名称</label>
                                    <div class="layui-input-block">
                                        <label>
                                            <input type="text" name="uuid" hidden="hidden">
                                            <input type="text" name="jbmc" placeholder="请输入表格名称"
                                                   autocomplete="off"
                                                   class="layui-input" style="width: 300px">
                                        </label>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">状态</label>
                                    <div class="layui-input-block">
                                        <label>
                                            <input type="checkbox" name="jbzt" lay-skin="switch" lay-filter="switch"
                                                   lay-text="有效|无效"
                                                   checked>
                                        </label>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <button id="uploadExcel" class="layui-btn">导入 Excel</button>
                                    <button id="submitBtn" class="layui-btn" lay-filter="submit" type="button">保存
                                    </button>
                                    <button id="btn_cancel" class="layui-btn layui-btn-primary">返回</button>
                                    <input id="fileInput" type="file" accept=".xlsx, .xls" style="display: none;">
                                    <div class="show_import_excel">
                                        ———————————— 导入excel表格预览 ————————————
                                    </div>
                                    <div class="table-wrapper">
                                        <table id="resultTable" class="layui-table"></table>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <!--主页面表格-->
                    <div class="case_table_div">
                        <table class="layui-hide" id="case_table" lay-filter="case_table"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
<!--新增静态建表-->
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addNewCase">新建静态表格</button>
    </div>
</script>
<!--调整-->
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script src="/layui/layui.all.js"></script>
<script src="/js/xlsx.full.min.js"></script>
<script src="/js/core.util.js"></script>
<script>
    //获取token
    var token = CoreUtil.getData("access_token");
    //地址栏转义token中的#号
    var tokenQuery = token.replace("#", "%23");
    var tableIns1;
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var upload = layui.upload;
    var $ = jQuery = layui.jquery;
    var laydate = layui.laydate;
    var tree = layui.tree;
    var startTime = null;
    var endTime = null;
    layui.config({
        base: '/'
    }).extend({
        eleTree: 'layui-ext/eleTree/eleTree'
    }).use(['table', 'laypage', 'layer', 'laydate', 'tree', 'eleTree', 'upload'], function () {
        tableIns1 = table.render({
            elem: '#case_table'
            , contentType: 'application/json'
            , headers: {"authorization": token}
            , page: true //开启分页
            , url: '/attention/zdgz/queryJtjbTable' //数据接口
            , method: 'POST'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                    "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                }
            }
            , cols: [
                [
                    {field: 'uuid', title: 'uuid', hide: true},
                    {field: 'jbmc', title: '建表名称', width: 400, align: "center", sort: true},
                    {
                        field: 'jbzt', title: '建表状态', width: 150, align: "center", templet: function (item) {
                            if (item.jbzt === "1") {
                                return '  <input type="checkbox" lay-skin="switch" lay-text="有效|无效" disabled checked>';
                            }
                            if (item.jbzt === "0") {
                                return '  <input type="checkbox" lay-skin="switch" lay-text="有效|无效" disabled>';
                            }
                        }
                    },
                    {
                        align: 'center',
                        width: 280,
                        field: 'lrrxm',
                        title: '录入人员',
                        sort: true
                    },
                    {
                        align: 'center',
                        width: 150,
                        field: 'lrrq',
                        title: '录入日期',
                        sort: true,
                        templet: function (d) {
                            // 格式化日期为 'yyyy-MM-dd'
                            return layui.util.toDateString(d.lrrq, 'yyyy-MM-dd');
                        }
                    },
                    {align: 'center', title: '操作', width: 250, toolbar: '#tool'}
                ]
            ]
            , toolbar: '#toolbar'
        });
        //新建表格
        table.on('toolbar(case_table)', function () {
            //清楚缓存
            resetForm();
            //隐藏表格
            $(".case_table_div").hide();
            //显示编辑窗口
            $(".operation_case").show();
            $(".title").html("新增静态表格");
            form.render(); //更新全部
        });
        //操作
        table.on('tool(case_table)', function (obj) {
            const data = obj.data;
            switch (obj.event) {
                case 'del':
                    delJtjb(data);
                    break;
                case 'edit':
                    $(".case_table_div").hide();
                    //显示编辑窗口
                    $(".operation_case").show();
                    $(".title").html("编辑静态表格");
                    getCaseDetail(data);
                    break;
            }
        });
        //修改方法
        let getCaseDetail = function (data) {
            $(".operation_case input[name=uuid]").val(data.uuid);
            $(".operation_case input[name=jbmc]").val(data.jbmc);
            // 判断状态并更新开关
            if (data.jbzt === "1") {
                updateSwitchStatus(true);  // 设置为有效状态
            } else {
                updateSwitchStatus(false); // 设置为失效状态
            }
            $("#resultTable").replaceWith(data.context);
            form.render(); //更新全部
        }
        //有效无效选择框
        form.on('switch(switch)', function () {
            $(".operation_case input[name=jbzt]").attr('type', 'hidden').val(this.checked ? 1 : 0);
        });
        //返回按钮
        $("#btn_cancel").click(function () {
            $(".case_table_div").show();
            $(".operation_case").hide();
            $(".operation_case_dataScope").hide();
            return false;
        });

        //判断页面更新状态
        function updateSwitchStatus(isValid) {
            // 更新 input 状态
            const $input = $(".operation_case input[name=jbzt]");
            $input.attr('type', 'hidden')
                .val(isValid ? 1 : 0)
                .prop('checked', isValid);

            // 更新开关的样式
            const $switch = $(".layui-unselect.layui-form-switch");
            const newClass = isValid ? "layui-unselect layui-form-switch layui-form-onswitch" : "layui-unselect layui-form-switch";
            $switch.attr("class", newClass);

            // 更新开关的文本
            const $text = $(".layui-unselect.layui-form-switch em");
            $text.text(isValid ? "有效" : "失效");
        }

        //清空页面缓存
        let resetForm = function () {
            // 清空表单中的所有输入框和开关状态
            $(".operation_case input[name = uuid]").val('');
            $(".operation_case input[name = jbmc]").val('');
            $(".operation_case table#resultTable").empty();
            updateSwitchStatus(true);  // 设置为打开状态
            layui.form.render();  // 更新layui表单
        }
        // 监听保存按钮点击事件
        $("#submitBtn").click(function () {
            // 获取表单中的所有值
            const formData = layui.form.val('deptInfo');
            formData.context = document.getElementById('resultTable').outerHTML;
            if (!formData.jbmc || formData.jbmc.trim() === "") {
                // 如果 jbmc 为空，弹出提示框
                layui.layer.msg('建表名称不能为空', {icon: 5});  // icon: 5 表示错误提示
                return;
            } else if (!formData.context || formData.context.trim() === "" || formData.context.trim() === "<table id=\"resultTable\" class=\"layui-table\"></table>") {
                layui.layer.msg('导入Excel不能为空', {icon: 5});  // icon: 5 表示错误提示
                return;
            }
            CoreUtil.sendPost("/attention/zdgz/saveJtjb", formData, function (res) {
                layer.msg(res.msg, {icon: 1, time: 1500}, function () {
                    // 提示关闭后再刷新页面
                    window.location.reload();
                });
            });

        });
        //监听提交 新增案件
        form.on('submit(submit)', function (event, data) {
            event.preventDefault();
            console.log("我进来了嘛？", data);
            var params = {
                id: data.field.id,
                name: data.field.name,
                status: data.field.status,
            }
            if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
                CoreUtil.sendPost("/attention/specialCaseManagement/add", params, function (res) {
                    $(".case_table_div").show();
                    $(".operation_case").hide();
                    $(".operation_case_dataScope").hide();
                    search();
                });
            } else {
                CoreUtil.sendPost("/attention/specialCaseManagement/update", params, function (res) {
                    //显示表格
                    $(".case_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_case").hide();
                    $(".operation_case_dataScope").hide();
                    search();
                });
            }
            return false;
        });
        //删除静态建表
        let delJtjb = function (data) {
            layer.open({
                content: '确定要删除么',
                yes: function (index) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendPost("/attention/zdgz/delJtjb", data, function (res) {
                        layer.msg(res.msg);
                        search();
                    });
                }
            });
        }
    });

    //执行查询
    function search() {
        tableIns1.reload({
            where: { //设定异步数据接口的额外参数，任意设
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

    //导入excel
    document.getElementById('uploadExcel').addEventListener('click', function () {
        document.getElementById('fileInput').click();
    });

    document.getElementById('fileInput').addEventListener('change', function (event) {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function (e) {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, {type: 'array'});

            // 默认读取第一个工作表
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const mergedCells = sheet['!merges'] || [];

            const tableData = XLSX.utils.sheet_to_json(sheet, {header: 1}); // 转换为二维数组

            const normalizedData = normalizeTableData(tableData); // 补全缺失单元格

            generateTable(normalizedData, mergedCells);
        };

        reader.readAsArrayBuffer(file);
    });

    function normalizeTableData(data) {
        const maxLength = Math.max(...data.map(row => row.length));
        return data.map(row => {
            const newRow = Array.from(row); // 复制当前行
            while (newRow.length < maxLength) {
                newRow.push(null); // 补充缺失的单元格
            }
            return newRow;
        });
    }

    function generateTable(data, merges) {
        const table = document.getElementById('resultTable');
        table.innerHTML = '';

        const mergedMap = new Map(); // 用于记录已处理的合并单元格

        merges.forEach(merge => {
            const key = `${merge.s.r},${merge.s.c}`;
            mergedMap.set(key, merge);
        });

        data.forEach((row, rowIndex) => {
            const tr = document.createElement('tr');

            row.forEach((cell, colIndex) => {
                // 检查当前单元格是否在合并区域中
                const key = `${rowIndex},${colIndex}`;
                if (mergedMap.has(key)) {
                    const merge = mergedMap.get(key);

                    const td = document.createElement('td');
                    td.rowSpan = merge.e.r - merge.s.r + 1;
                    td.colSpan = merge.e.c - merge.s.c + 1;
                    td.textContent = cell != null && cell !== '' ? cell : '-';
                    tr.appendChild(td);
                } else if (!isInMergedRegion(rowIndex, colIndex, merges)) {
                    const td = document.createElement('td');
                    td.textContent = cell != null && cell !== '' ? cell : '-';
                    tr.appendChild(td);
                }
            });

            table.appendChild(tr);
        });
    }

    function isInMergedRegion(row, col, merges) {
        return merges.some(merge => {
            return row >= merge.s.r && row <= merge.e.r && col >= merge.s.c && col <= merge.e.c;
        });
    }

</script>
</html>